const { db } = require('../db');
const { getRedisValue, setRedisValue } = require('../db/redis')
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const moment = require('moment');
const { SECRET_KEY, EXPIRES_IN } = require('../config');
const nodemailer = require('nodemailer');
const { resolve } = require('path');
const { json } = require('stream/consumers');
const { getWXaCode, getWXUserInfo, getWXUserInfo2 } = require('../routerHandler/wechat');

const transporter = nodemailer.createTransport({
    service: 'QQ',
    auth: {
        user: '807132689@qq.com',
        pass: 'snpbvahojjnubcbf'
    }
});

exports.getUserInfo = async (req, res) => {
    const email = req.auth.email;
    const sql = "select * from users where email=?";
    db.query(sql, email, (err, results) => {
        if (err) {
            return res.send({
                status: 500,
                msg: err.message
            })
        } else if (results.length > 0) {
            return res.send({
                status: 200,
                msg: 'success',
                data: resultsWithCamelCase(results[0])
            })
        } else {
            return res.send({
                status: 400,
                msg: '用户不存在'
            });
        }
    });
}

exports.register = async (req, res) => {
    const userInfo = req.body;
    const code = userInfo.verificationCode;
    const redisCode = await getRedisValue(userInfo.email);
    if (code == redisCode) {
        const sql = "select * from users where email=?";
        db.query(sql, userInfo.email, (err, results) => {
            if (err) {
                return res.send({
                    status: 500,
                    msg: err.message
                })
            }
            if (results.length > 0) {
                return res.send({
                    status: 400,
                    msg: '邮箱已存在'
                })
            }
            userInfo.password = bcrypt.hashSync(userInfo.password, 10);
            const sql = "insert into users set avatar=?, email=?, password=?";
            db.query(sql, [imgUrl(), userInfo.email, userInfo.password], (err, results) => {
                if (err) {
                    return res.send({
                        status: 500,
                        msg: err.message
                    })
                }else if (results.affectedRows == 1) {
                    const token = jwt.sign({
                        email: userInfo.email
                    }, SECRET_KEY, {
                        algorithm: 'HS256',
                        expiresIn: 60 * 60 * 24
                    });
                    return res.send({
                        status: 200,
                        msg: '注册成功，将为你自动登录',
                        token: 'Bearer ' + token
                    })
                } else {
                    return res.send({
                        status: 500,
                        msg: '注册失败，请稍后重试'
                    })
                }
            });
        })
    } else {
        return res.send({
            status: 400,
            msg: '验证码错误或已过期'
        });
    }
}

exports.login = (req, res) => {
    const userInfo = req.body;
    const sql = "select * from users where email=?";
    db.query(sql, userInfo.email, (err, results) => {
        if (err) {
            return res.send({
                status: 500,
                msg: err.message
            })
        } else if (results.length != 1) {
            return res.send({
                status: 403,
                msg: '登录失败，请检查用户名和密码！'
            })
        } else {
            const flag = bcrypt.compareSync(userInfo.password, results[0].password);
            if (!flag) {
                return res.send({
                    status: 403,
                    msg: '登录失败，密码错误'
                })
            } else {
                const token = jwt.sign({
                    email: req.body.email
                }, SECRET_KEY, {
                    algorithm: 'HS256',
                    expiresIn: 60 * 60 * 24
                });
                res.send({
                    status: 200,
                    msg: '登录成功！',
                    token: 'Bearer ' + token
                });
            }
        }
    });
}

exports.verificationCode = async (req, res) => {
    const email = req.query.email;
    const info = await sendMail(email);
    if (info && info.response && info.response.includes('250 OK')) {
        return res.send({
            status: 200,
            msg: '验证码已发送'
        });
    } else {
        return res.send({
            status: 500,
            msg: '验证码发送失败，请稍后重试'
        });
    }
}

const sendMail = async (email) => {
    const code = generateRandomSixDigitNumber();
    const mailOptions = {
        from: '【黄老师的ChatGPT】<807132689@qq.com>',
        to: email,
        subject: '验证码',
        html: `<b style="font-size:28px">您的验证码为：<span style="color:red">${code}</span> ，请在10分钟内输入</b> <br /><br /><br /> \
        <b style="font-size:28px;color:green">关注公众号【MasterH杂货铺】，获取最新AI新闻与工具</b> \
        <img src="https://image.xiaosaturn.com/2023/hsftyt.jpg"></img>`
    };
    return new Promise((resolve, reject) => {
        transporter.sendMail(mailOptions, function (error, info) {
            if (error) {
                console.log(error);
                reject(error);
            } else {
                setRedisValue(email, code, 600);
                resolve(info);
            }
        });
    })
}

exports.addCount = async (req, res) => {
    const result = await getWXUserInfo2(req.body.wxcode);
    if (result && result.code != 200) {
        // 为了防止接口被过度使用，必须在微信小程序环境下使用
        return res.send({
            code: 500,
            msg: result.msg
        });
    }
    const results = await queryCountByUserId(req.query.userId);
    if (results.length == 1) {
        const result = JSON.stringify(results[0]);
        const jsonObj = JSON.parse(result);
        const updateTime = moment(new Date()).utcOffset(8).format('YYYY-MM-DD HH:mm:ss');
        const sql = "update users set can_problem_count=?, total_problem_count=?, update_time=? where id=?";
        db.query(sql, [jsonObj.can_problem_count + 5, jsonObj.total_problem_count + 5, updateTime, req.query.userId], (err, results) => {
            if (err) {
                return res.send({
                    code: 500,
                    msg: err.message
                })
            }
            return res.send({
                code: 200,
                msg: '更新成功'
            })
        })
    } else {
        return res.send({
            code: 500,
            msg: '更新失败'
        })
    }
}

exports.subCanProblemCount = async (req, res) => {
    const results = await queryCountByEmail(req.auth.email);
    if (results.length == 1) {
        const result = JSON.stringify(results[0]);
        const jsonObj = JSON.parse(result);
        if (jsonObj.can_problem_count > 0) {
            const sql = "update users set can_problem_count=? where email=?";
            db.query(sql, [jsonObj.can_problem_count - 1, req.auth.email], (err, results) => {
                if (err) {
                    return res.send({
                        status: 500,
                        msg: err.message
                    })
                }
                return res.send({
                    status: 200,
                    msg: '更新成功',
                    data: {
                        count: jsonObj.can_problem_count - 1
                    }
                })
            })
        } else {
            return res.send({
                status: 500,
                msg: '次数用完了，请至个人中心观看广告，获取次数'
            })
        }
    } else {
        return res.send({
            status: 500,
            msg: '更新失败'
        })
    }
}

const queryCountByEmail = async (email) => {
    const sql = "select can_problem_count, total_problem_count from users where email=?";
    return new Promise((resolve, reject) => {
        db.query(sql, email, (err, results) => {
            if (err) {
                reject(err);
            } else {
                resolve(results);
            }
        })
    })
}

const queryCountByUserId = async (userId) => {
    const sql = "select can_problem_count, total_problem_count from users where id=?";
    return new Promise((resolve, reject) => {
        db.query(sql, userId, (err, results) => {
            if (err) {
                reject(err);
            } else {
                resolve(results);
            }
        })
    })
}

// 生成随机六位数
const generateRandomSixDigitNumber = () => {
    var min = 100000; // 最小值（六位数的最小值是100000）
    var max = 999999; // 最大值（六位数的最大值是999999）
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

// 假设results是查询结果数组
const resultsWithCamelCase = (result) => {
    const newRow = {};
    Object.keys(result).forEach(key => {
        const camelCaseKey = key.replace(/_([a-z])/g, function (m, p1) {
            return p1.toUpperCase();
        });
        newRow[camelCaseKey] = result[key];
    });
    return newRow;
};

const imgUrl = function () {
    const randomNum = Math.floor(Math.random() * 50) + 1;
    return `https://image.xiaosaturn.com/avatar/avatar-${randomNum}.png`;
}